package com.kunlun.basedata.controller;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ziweizhang
 * @Date 2021/4/9 14:23
 */
@RestController
@RequestMapping("/activiti")
public class ActivitiDemoController {

    private static final Logger log = LoggerFactory.getLogger(ActivitiModeController.class);

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    /**
     * 部署方式一:
     * 这里直接以现有资源的方式进行部署
     */
    @RequestMapping("/demo")
    public void deployActivitiInfo() {
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("template/MyDemo.bpmn")   // bpmn文件
                .addClasspathResource("template/MyDemo.png")    // 图片文件
                .name("请假审批流程")
                .category("办公类别")
                .deploy();

        log.info("流程名称: {}", deploy.getName());
        log.info("流程部署ID: {}", deploy.getId());

    }
    @RequestMapping("/deteleDemo")
    public String deleteProcessDefinition() {
        // 根据流程定义的key删除流程定义
        // 查询指定key的所有版本的流程定义
        List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery().processDefinitionKey
                ("myProcess_1").list();
        for (ProcessDefinition processDefinition : pdList) {
            // 级联删除指定key的所有版本
            repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true);
        }
        return "delete success";
    }
    @RequestMapping("/startDemo")
    public String startProcess() {
        Map<String, Object> variables = new HashMap<>();
        variables.put("userId", "张三");
        // 启动流程，同时设置变量（因为第一个任务节点的指定人是通过变量的方式获取的）
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("myProcess_1", variables);
        log.info("pid:{}={}", pi.getId(), pi.getProcessInstanceId());
        return "pid:" + pi.getId();
    }
    @RequestMapping("/taskDemo")
    public String getTask(String userId) {
        List<Task> taskList = taskService.createTaskQuery()// 创建任务查询对象
                .taskAssignee(userId)// 指定个人任务办理人
                .list();
        for (Task task : taskList) {
            log.info("taskId:{};taskName:{};pid:{}", task.getId(), task.getName(), task.getProcessInstanceId());
        }
        return taskList.toString();
    }
}
